import {ACCESS_TOKEN,USER_ID,OPENID} from '@/store/mutation-types'
import storage from '@/utils/storage'
import * as LoginApi from '@/api/login'

// 登陆成功后执行
const loginSuccess = (commit, {
	access_token,
	user_id,
	openid
}) => {
	// 过期时间30天
	const expiryTime = 30 * 86400
	// 保存tokne和user_id到缓存
	storage.set(USER_ID, user_id, expiryTime)
	storage.set(ACCESS_TOKEN, access_token, expiryTime)
	storage.set(OPENID, openid, expiryTime)
	// 记录到store全局变量
	commit('SET_TOKEN', access_token)
	commit('SET_USER_ID', user_id)
	commit('SET_OPENID', openid)
}

const user = {
	state: {
		// 用户认证access_token
		access_token: '',
		// 用户ID
		user_id: null,
		openid:''
	},

	mutations: {
		SET_TOKEN: (state, value) => {
			state.access_token = value
		},
		SET_USER_ID: (state, value) => {
			state.user_id = value
		},
		SET_OPENID: (state, value) => {
			state.openid = value
		}
	},

	actions: {
		// 用户登录(普通登录: 输入手机号和验证码)
		Login({commit}, data) {
			return new Promise((resolve, reject) => {
				LoginApi.smsLogin(data)
					.then(response => {
						const result = response.data
						loginSuccess(commit, result)
						resolve(response)
					})
					.catch(reject)
			})
		},

		// 微信小程序一键授权登录(获取用户基本信息)
		LoginMpWx({commit}, data) {
			return new Promise((resolve, reject) => {
				LoginApi.getOpenid(
						data
					, {
						isPrompt: false
					})
					.then(response => {
						const result = response.data
						loginSuccess(commit, result)
						resolve(response)
					})
					.catch(reject)
			})
		},

		// 微信小程序一键授权登录(授权手机号)
		LoginMpWxMobile({commit}, data) {
			return new Promise((resolve, reject) => {
				LoginApi.getPhone(data, {
						isPrompt: false
					})
					.then(response => {
						const result = response.data
						loginSuccess(commit, result)
						resolve(response)
					})
					.catch(reject)
			})
		},

		// 退出登录
		Logout({commit}, data) {
			const store = this
			return new Promise((resolve, reject) => {
				if (store.getters.user_id > 0) {
					// 删除缓存中的tokne和user_id
					storage.remove(USER_ID)
					storage.remove(ACCESS_TOKEN)
					// 记录到store全局变量
					commit('SET_TOKEN', '')
					commit('SET_USER_ID', null)
					resolve()
				}
			})
		}

	}
}

export default user
